package com.project.school_flate.serviceimpl.order;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.GsonBuilder;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.project.school_flate.config.activemq.DelayedActive;
import com.project.school_flate.entity.com.ComPayFlow;
import com.project.school_flate.entity.flow.table.FlowBusinessTableDef;
import com.project.school_flate.util.wechat.WxMessagesManager;
import com.project.school_flate.dto.order.OrderTakeawayDto;
import com.project.school_flate.entity.com.ComDistributionRule;
import com.project.school_flate.entity.com.ComSchool;
import com.project.school_flate.entity.com.ComSchoolBuilding;
import com.project.school_flate.entity.com.table.ComDistributionRuleTableDef;
import com.project.school_flate.entity.delivery.DeliveryInfo;
import com.project.school_flate.entity.delivery.table.DeliveryInfoTableDef;
import com.project.school_flate.entity.flow.FlowBusiness;
import com.project.school_flate.entity.flow.FlowMoney;
import com.project.school_flate.entity.flow.FlowTask;
import com.project.school_flate.entity.flow.table.FlowMoneyTableDef;
import com.project.school_flate.entity.order.OrderDelivery;
import com.project.school_flate.entity.order.OrderTakeaway;
import com.project.school_flate.entity.order.OrderTakeawayCommodity;
import com.project.school_flate.entity.order.OrderTakeawaySaveCache;
import com.project.school_flate.entity.order.table.OrderDeliveryTableDef;
import com.project.school_flate.entity.order.table.OrderTakeawayCommodityTableDef;
import com.project.school_flate.entity.order.table.OrderTakeawayTableDef;
import com.project.school_flate.entity.shop.ShopCommodity;
import com.project.school_flate.entity.shop.ShopInfo;
import com.project.school_flate.entity.shop.ShopRule;
import com.project.school_flate.entity.shop.ShopSaveUser;
import com.project.school_flate.entity.shop.table.ShopRuleTableDef;
import com.project.school_flate.entity.shop.table.ShopSaveUserTableDef;
import com.project.school_flate.entity.table.com.ComSchoolBuildingTable;
import com.project.school_flate.entity.table.com.ComSchoolTable;
import com.project.school_flate.entity.table.flow.FlowBusinessTable;
import com.project.school_flate.entity.table.order.OrderTakeawayTable;
import com.project.school_flate.entity.table.shop.ShopInfoTable;
import com.project.school_flate.entity.table.user.UserInfoTable;
import com.project.school_flate.entity.user.UserAddress;
import com.project.school_flate.entity.user.UserInfo;
import com.project.school_flate.entity.user.table.UserInfoTableDef;
import com.project.school_flate.mapper.com.ComDistributionRuleMapper;
import com.project.school_flate.mapper.com.ComSchoolBuildingMapper;
import com.project.school_flate.mapper.com.ComSchoolMapper;
import com.project.school_flate.mapper.delivery.DeliveryInfoMapper;
import com.project.school_flate.mapper.flow.FlowBusinessMapper;
import com.project.school_flate.mapper.flow.FlowMoneyMapper;
import com.project.school_flate.mapper.flow.FlowTaskMapper;
import com.project.school_flate.mapper.order.OrderDeliveryMapper;
import com.project.school_flate.mapper.order.OrderTakeawayCommodityMapper;
import com.project.school_flate.mapper.order.OrderTakeawayMapper;
import com.project.school_flate.mapper.order.OrderTakeawaySaveCacheMapper;
import com.project.school_flate.mapper.shop.ShopCommodityMapper;
import com.project.school_flate.mapper.shop.ShopInfoMapper;
import com.project.school_flate.mapper.shop.ShopRuleMapper;
import com.project.school_flate.mapper.shop.ShopSaveUserMapper;
import com.project.school_flate.mapper.user.UserAddressMapper;
import com.project.school_flate.mapper.user.UserInfoMapper;
import com.project.school_flate.service.com.WeiXinPayService;
import com.project.school_flate.service.order.OrderTakeawayService;
import com.project.school_flate.util.DateUtils;
import com.project.school_flate.util.PoToDTO;
import com.project.school_flate.util.QRCodeUtil;
import com.project.school_flate.util.Result.Result;
import com.project.school_flate.util.system.ComVariableUtil;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 *  服务层实现。
 *
 * @author 马维健
 * @since 2024/1/2
 */
@Service
public class OrderTakeawayServiceImpl extends ServiceImpl<OrderTakeawayMapper, OrderTakeaway> implements OrderTakeawayService {

    @Autowired
    private OrderTakeawayMapper oOrderTakeawayMapper;

    @Autowired
    private DeliveryInfoMapper oDeliveryInfoMapper;

    @Autowired
    private ComSchoolBuildingMapper oComSchoolBuildingMapper;

    @Autowired
    private OrderTakeawayCommodityMapper oOrderTakeawayCommodityMapper;

    @Autowired
    private ShopCommodityMapper oShopCommodityMapper;

    @Autowired
    private ShopInfoMapper oShopInfoMapper;

    @Autowired
    private WeiXinPayService oWeiXinPayService;

    @Autowired
    private ShopSaveUserMapper oShopSaveUserMapper;

    @Autowired
    private FlowBusinessMapper oFlowBusinessMapper;

    @Autowired(required = false)
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private FlowTaskMapper oFlowTaskMapper;

    @Autowired
    private FlowMoneyMapper oFlowMoneyMapper;

    @Autowired
    private UserInfoMapper oUserInfoMapper;

    @Autowired
    private ComSchoolMapper oComSchoolMapper;

    @Autowired
    private ComDistributionRuleMapper oComDistributionRuleMapper;

    @Autowired
    private ShopRuleMapper oShopRuleMapper;

    @Autowired
    private UserAddressMapper oUserAddressMapper;

    @Autowired
    private OrderTakeawaySaveCacheMapper oOrderTakeawaySaveCacheMapper;

    @Autowired
    private OrderDeliveryMapper oOrderDeliveryMapper;

    @Autowired
    private WxMessagesManager wxMessagesManager;

    /**
     * 获取外卖订单
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getOrderTakeaway(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        List<OrderTakeaway> oOrderTakeawayList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入配送员ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getDeliveryId())){
            QueryWrapper qrOrderDelivery = new QueryWrapper();
            qrOrderDelivery.where(OrderDeliveryTableDef.ORDER_DELIVERY.DELIVERY_ID.eq(oOrderTakeawayDto.getDeliveryId()));
            List<OrderDelivery> oOrderDeliveryList = oOrderDeliveryMapper.selectListByQuery(qrOrderDelivery);
            if(CollectionUtils.isEmpty(oOrderDeliveryList)){
                return Result.ok(new ArrayList(),total);
            }
            //获取查到的订单ID集合
            List<String> oOrderTakeawayIdList = new ArrayList<>();
            oOrderDeliveryList.forEach(item->{oOrderTakeawayIdList.add(item.getOrderTakeawayId());});
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.ID.in(oOrderTakeawayIdList));
        }
        //判断是否传入店铺ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getShopId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_ID.eq(oOrderTakeawayDto.getShopId()));
        }
        //判断是否传入用户ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getUserId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.USER_ID.eq(oOrderTakeawayDto.getUserId()));
        }
        //判断是否传入支付状态
        if(oOrderTakeawayDto.getPayState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(oOrderTakeawayDto.getPayState()));
        }
        //判断是否传入配送状态
        if(oOrderTakeawayDto.getDeliveryState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(oOrderTakeawayDto.getDeliveryState()));
        }
        //判断是否传入出餐状态
        if(oOrderTakeawayDto.getShopState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_STATE.eq(oOrderTakeawayDto.getShopState()));
        }
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oOrderTakeawayDto.getPage() != null && oOrderTakeawayDto.getLimit() != null){
            Page<OrderTakeaway> OrderTakeawayPage = oOrderTakeawayMapper.paginateWithRelations(oOrderTakeawayDto.getPage(),oOrderTakeawayDto.getLimit(),queryWrapper);
            oOrderTakeawayList = OrderTakeawayPage.getRecords();
            total = OrderTakeawayPage.getTotalRow();
        }else{
            oOrderTakeawayList = oOrderTakeawayMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oOrderTakeawayList.size();
        }
        //PoToDto
        List<OrderTakeawayDto> oOrderTakeawayDtoList = (List<OrderTakeawayDto>) PoToDTO.poToDtoList(oOrderTakeawayList,new OrderTakeawayDto());
        return Result.ok(oOrderTakeawayDtoList,total);
    }

    /**
     * 添加外卖订单
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result addOrderTakeaway(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        OrderTakeaway oOrderTakeaway = new OrderTakeaway();
        PoToDTO.poToDto(oOrderTakeawayDto,oOrderTakeaway);
        //判断是否填入地址信息
        if(StringUtils.isBlank(oOrderTakeaway.getUserAddress())){
            return Result.error("请填写配送地址");
        }
        //获取店铺信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopInfoTable.SHOP_INFO.ID.eq(oOrderTakeaway.getShopInfo()));
        queryWrapper.where(ShopInfoTable.SHOP_INFO.STATE.eq(1));
        ShopInfo oShopInfo = oShopInfoMapper.selectOneByQuery(queryWrapper);
        if(oShopInfo == null){
            return Result.error("店铺不存在");
        }
        //获取用户信息
        queryWrapper = new QueryWrapper();
        queryWrapper.where(UserInfoTable.USER_INFO.ID.eq(oOrderTakeaway.getUserId()));
        queryWrapper.where(UserInfoTable.USER_INFO.STATE.eq(1));
        UserInfo oUserInfo = oUserInfoMapper.selectOneByQuery(queryWrapper);
        if(oUserInfo == null){
            return Result.error("客户不存在");
        }
        //获取校园信息
        queryWrapper = new QueryWrapper();
        queryWrapper.where(ComSchoolTable.COM_SCHOOL.ID.eq(oOrderTakeaway.getSchoolId()));
        queryWrapper.where(ComSchoolTable.COM_SCHOOL.STATE.eq(1));
        ComSchool oComSchool = oComSchoolMapper.selectOneByQuery(queryWrapper);
        if(oComSchool == null){
            return Result.error("校园不存在");
        }
        //获取校园楼栋
        queryWrapper = new QueryWrapper();
        queryWrapper.where(ComSchoolBuildingTable.COM_SCHOOL_BUILDING.ID.eq(oOrderTakeaway.getSchoolBuildingId()));
        queryWrapper.where(ComSchoolBuildingTable.COM_SCHOOL_BUILDING.STATE.eq(1));
        ComSchoolBuilding oComSchoolBuilding = oComSchoolBuildingMapper.selectOneByQuery(queryWrapper);
        if(oComSchoolBuilding == null){
            return Result.error("校园楼栋不存在");
        }
        if(oOrderTakeawayMapper.insert(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加外卖订单失败");
        }
        //添加外卖订单商品
        if(CollectionUtils.isNotEmpty(oOrderTakeawayDto.getOrderTakeawayCommodityList())){
            for(OrderTakeawayCommodity oOrderTakeawayCommodity : oOrderTakeawayDto.getOrderTakeawayCommodityList()){
                oOrderTakeawayCommodity.setOrderTakeawayId(oOrderTakeaway.getId());
            }
            if(oOrderTakeawayCommodityMapper.insertBatch(oOrderTakeawayDto.getOrderTakeawayCommodityList()) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("添加外卖订单商品失败");
            }
        }
        //创建业务流水
        FlowBusiness oFlowBusiness = new FlowBusiness();
        oFlowBusiness.setType(0);
        oFlowBusiness.setUserId(oOrderTakeaway.getUserId());
        oFlowBusiness.setShopId(oOrderTakeaway.getShopId());
        oFlowBusiness.setInflowDirection(0);
        oFlowBusiness.setInflowWay(0);
        oFlowBusiness.setOrderId(oOrderTakeaway.getId());
        oFlowBusiness.setMoney(oOrderTakeaway.getPrice());
        if(oFlowBusinessMapper.insert(oFlowBusiness) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加外卖订单失败");
        }
        //修改配送地址最近使用时间
        UserAddress oUserAddress = new UserAddress();
        oUserAddress.setId(oOrderTakeawayDto.getUserAddressId());
        oUserAddress.setRecentlyTime(new Date());
        if(oUserAddressMapper.update(oUserAddress) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加外卖订单失败");
        }
        //限制支付时间自动删除订单
        long delay = 10 * 60 * 1000;
        new DelayedActive().delaySend(new ActiveMQQueue("automaticDeleteOrderTakeaway"),oOrderTakeaway.getId(),delay);
        return Result.ok(oOrderTakeaway.getId());
    }

    /**
     * 修改外卖订单
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result updateOrderTakeaway(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        OrderTakeaway oOrderTakeaway = new OrderTakeaway();
        PoToDTO.poToDto(oOrderTakeawayDto,oOrderTakeaway);
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改外卖订单失败");
        }
        return Result.ok("修改外卖订单成功");
    }

    /**
     * 删除外卖订单
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result deleteOrderTakeaway(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        OrderTakeaway oOrderTakeaway = new OrderTakeaway();
        PoToDTO.poToDto(oOrderTakeawayDto,oOrderTakeaway);
        //删除储蓄支付业务流水
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(FlowBusinessTable.FLOW_BUSINESS_TABLE.ORDER_ID.eq(oOrderTakeaway.getId()));
        if(oFlowBusinessMapper.deleteByQuery(queryWrapper) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("删除外卖订单失败");
        }
        //删除支付订单商品
        queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayCommodityTableDef.ORDER_TAKEAWAY_COMMODITY.ORDER_TAKEAWAY_ID.eq(oOrderTakeaway.getId()));
        if(oOrderTakeawayCommodityMapper.deleteByQuery(queryWrapper) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("删除外卖订单失败");
        }
        //删除支付订单
        if(oOrderTakeawayMapper.deleteById(oOrderTakeaway.getId()) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("删除外卖订单失败");
        }
        return Result.ok("删除外卖订单成功");
    }

    /**
     * 店铺出餐
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result diningOrderTakeawayToShop(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        try {
            automaticDiningOrderTakeawayToShop(oOrderTakeawayDto.getId());
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 店铺自动出餐
     * @param oOrderTakeawayId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public void automaticDiningOrderTakeawayToShop(String oOrderTakeawayId) throws Exception {
        if(StringUtils.isBlank(oOrderTakeawayId)){
            throw new Exception("店铺出餐失败");
        }
        //重新获取订单
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.ID.eq(oOrderTakeawayId));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.PAY_STATE.eq(1));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.SHOP_STATE.eq(0));
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneByQuery(queryWrapper);
        if(oOrderTakeaway == null){
            throw new Exception("订单已出餐或被取消");
        }
        oOrderTakeaway.setShopState(1);
        oOrderTakeaway.setDiningTime(new Date());
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("店铺出餐失败");
        }
    }

    /**
     * 获取外卖订单大厅（配送员）
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getOrderTakeawayHallToDelivery(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        //获取登陆配送员
        if(StringUtils.isBlank(oOrderTakeawayDto.getDeliveryId())){
            return Result.error("请重新登录");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.ID.eq(oOrderTakeawayDto.getDeliveryId()));
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.STATE.eq(1));
        DeliveryInfo oDeliveryInfo = oDeliveryInfoMapper.selectOneByQuery(queryWrapper);
        if(oDeliveryInfo == null){
            return Result.error("配送员不存在");
        }
        if(oDeliveryInfo.getExamineState() == 0){
            return Result.error("请先前往审核");
        }
//        //获取适合的学校楼栋
//        queryWrapper = new QueryWrapper();
//        queryWrapper.where(ComSchoolBuildingTable.COM_SCHOOL_BUILDING.SCHOOL_ID.eq(oDeliveryInfo.getSchoolId()));
//        queryWrapper.where(ComSchoolBuildingTable.COM_SCHOOL_BUILDING.TYPE.in(oDeliveryInfo.getSex(),2));
//        List<ComSchoolBuilding> oComSchoolBuildingList = oComSchoolBuildingMapper.selectListByQuery(queryWrapper);
//        //创建外卖订单集合
//        List<OrderTakeaway> oOrderTakeawayList = new ArrayList<>();
//        long total = 0;
//        if(CollectionUtils.isNotEmpty(oComSchoolBuildingList)){
//            //获取适合的学校楼栋ID集合
//            List<String> oComSchoolBuildingIdList = new ArrayList<>();
//            oComSchoolBuildingList.forEach(item->{
//                oComSchoolBuildingIdList.add(item.getId());
//            });
//            queryWrapper = new QueryWrapper();
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(0));
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_ID.eq(oDeliveryInfo.getSchoolId()));
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_BUILDING_ID.in(oComSchoolBuildingIdList));
////            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.CREATE_TIME.le(DateUtils.getNowMinute(5)));
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(1));
//            queryWrapper.orderBy("create_time desc");
//            //是否分页
//            if(oOrderTakeawayDto.getPage() != null && oOrderTakeawayDto.getLimit() != null){
//                Page<OrderTakeaway> OrderTakeawayPage = oOrderTakeawayMapper.paginateWithRelations(oOrderTakeawayDto.getPage(),oOrderTakeawayDto.getLimit(),queryWrapper);
//                oOrderTakeawayList = OrderTakeawayPage.getRecords();
//                total = OrderTakeawayPage.getTotalRow();
//            }else{
//                oOrderTakeawayList = oOrderTakeawayMapper.selectListWithRelationsByQuery(queryWrapper);
//                total = oOrderTakeawayList.size();
//            }
//        }
        //创建外卖订单集合
        List<OrderTakeaway> oOrderTakeawayList = new ArrayList<>();
        long total = 0;
        queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(0));
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_ID.eq(oDeliveryInfo.getSchoolId()));
//        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.CREATE_TIME.le(DateUtils.getNowMinute(5)));
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(1));
        queryWrapper.orderBy("pay_time desc");
        //是否分页
        if(oOrderTakeawayDto.getPage() != null && oOrderTakeawayDto.getLimit() != null){
            Page<OrderTakeaway> OrderTakeawayPage = oOrderTakeawayMapper.paginateWithRelations(oOrderTakeawayDto.getPage(),oOrderTakeawayDto.getLimit(),queryWrapper);
            oOrderTakeawayList = OrderTakeawayPage.getRecords();
            total = OrderTakeawayPage.getTotalRow();
        }else{
            oOrderTakeawayList = oOrderTakeawayMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oOrderTakeawayList.size();
        }
        //PoToDto
        List<OrderTakeawayDto> oOrderTakeawayDtoList = (List<OrderTakeawayDto>) PoToDTO.poToDtoList(oOrderTakeawayList,new OrderTakeawayDto());
        return Result.ok(oOrderTakeawayDtoList,total);
    }

    /**
     * 配送员抢单
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public synchronized Result robOrderTakeawayToDelivery(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        //获取订单信息
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneById(oOrderTakeawayDto.getId());
        //判断订单是否被抢
        if(oOrderTakeaway.getDeliveryState() != 0){
            return Result.error("订单已被抢走");
        }
        //获取登陆配送员
        if(StringUtils.isBlank(oOrderTakeawayDto.getDeliveryId())){
            return Result.error("请重新登录");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.ID.eq(oOrderTakeawayDto.getDeliveryId()));
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.STATE.eq(1));
        DeliveryInfo oDeliveryInfo = oDeliveryInfoMapper.selectOneByQuery(queryWrapper);
        if(oDeliveryInfo == null){
            return Result.error("配送员不存在");
        }
        if(oDeliveryInfo.getExamineState() == 0){
            return Result.error("请先前往审核");
        }
        oOrderTakeaway.setDeliveryState(1);
        oOrderTakeaway.setConnectTime(new Date());
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("抢单失败");
        }
        //添加外卖订单配送
        OrderDelivery oOrderDelivery = new OrderDelivery();
        oOrderDelivery.setOrderTakeawayId(oOrderTakeaway.getId());
        oOrderDelivery.setDeliveryId(oOrderTakeawayDto.getDeliveryId());
        oOrderDelivery.setDeliveryState(0);
        if(oOrderDeliveryMapper.insert(oOrderDelivery) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("抢单失败");
        }
        //添加配送员业务流水
        UpdateChain.of(FlowBusiness.class)
                .set(FlowBusiness::getDeliveryId, oDeliveryInfo.getId())
                .where(FlowBusiness::getOrderId).eq(oOrderTakeaway.getId())
                .update();
        //判断配送员是否是兼职
        if(oDeliveryInfo.getWorkType() == 0){
            //添加配送员金额流水
            FlowMoney oFlowMoney = new FlowMoney();
            oFlowMoney.setType(0);
            oFlowMoney.setInflowWay(0);
            oFlowMoney.setOrderId(oOrderTakeaway.getId());
            //获取兼职配送员每单收益
            oFlowMoney.setMoney(Double.valueOf(ComVariableUtil.getSystemValue("delivery_draw")));
            oFlowMoney.setDeliveryId(oDeliveryInfo.getId());
            oFlowMoney.setInflowDirection(1);
            if(oFlowMoneyMapper.insert(oFlowMoney) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("抢单失败");
            }
        }
        return Result.ok("抢单成功");
    }

    /**
     * 配送员自动抢单
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Result automaticRobOrderTakeawayToDelivery(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        //获取配送员当前能抢的一单
        //获取登陆配送员
        if(StringUtils.isBlank(oOrderTakeawayDto.getDeliveryId())){
            return Result.error("请重新登录");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.ID.eq(oOrderTakeawayDto.getDeliveryId()));
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.STATE.eq(1));
        DeliveryInfo oDeliveryInfo = oDeliveryInfoMapper.selectOneByQuery(queryWrapper);
        if(oDeliveryInfo == null){
            return Result.error("配送员不存在");
        }
        if(oDeliveryInfo.getExamineState() == 0){
            return Result.error("请先前往审核");
        }
//        //获取适合的学校楼栋
//        queryWrapper = new QueryWrapper();
//        queryWrapper.where(ComSchoolBuildingTable.COM_SCHOOL_BUILDING.SCHOOL_ID.eq(oDeliveryInfo.getSchoolId()));
//        queryWrapper.where(ComSchoolBuildingTable.COM_SCHOOL_BUILDING.TYPE.in(oDeliveryInfo.getSex(),2));
//        List<ComSchoolBuilding> oComSchoolBuildingList = oComSchoolBuildingMapper.selectListByQuery(queryWrapper);
//        if(CollectionUtils.isNotEmpty(oComSchoolBuildingList)){
//            //获取适合的学校楼栋ID集合
//            List<String> oComSchoolBuildingIdList = new ArrayList<>();
//            oComSchoolBuildingList.forEach(item->{
//                oComSchoolBuildingIdList.add(item.getId());
//            });
//            List<OrderTakeaway> oOrderTakeawayList = new ArrayList<>();
//            long total = 0;
//            queryWrapper = new QueryWrapper();
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(0));
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_ID.eq(oDeliveryInfo.getSchoolId()));
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_BUILDING_ID.in(oComSchoolBuildingIdList));
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.CREATE_TIME.le(DateUtils.getNowMinute(5)));
//            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(1));
//            queryWrapper.orderBy("pay_time asc");
//            queryWrapper.limit(1);
//            queryWrapper.orderBy("create_time desc");
//            OrderTakeaway robOrderTakeaway = oOrderTakeawayMapper.selectOneByQuery(queryWrapper);
//            if(robOrderTakeaway != null){
//                robOrderTakeaway.setDeliveryId(oDeliveryInfo.getId());
//                robOrderTakeaway.setDeliveryState(1);
//                robOrderTakeaway.setConnectTime(new Date());
//                if(oOrderTakeawayMapper.update(robOrderTakeaway) == 0){
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return Result.error("抢单失败");
//                }
//                //添加配送员业务流水
//                FlowBusiness oFlowBusiness = new FlowBusiness();
//                oFlowBusiness.setDeliveryId(oDeliveryInfo.getId());
//                queryWrapper = new QueryWrapper();
//                queryWrapper.where(FlowBusinessTableDef.FLOW_BUSINESS.ORDER_ID.eq(robOrderTakeaway.getId()));
//                if(oFlowBusinessMapper.updateByQuery(oFlowBusiness,queryWrapper) == 0){
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    return Result.error("抢单失败");
//                }
//                //判断配送员是否是兼职
//                if(oDeliveryInfo.getWorkType() == 0){
//                    //添加配送员金额流水
//                    FlowMoney oFlowMoney = new FlowMoney();
//                    oFlowMoney.setType(0);
//                    oFlowMoney.setInflowWay(0);
//                    oFlowMoney.setOrderId(oOrderTakeaway.getId());
//                    oFlowMoney.setMoney(oOrderTakeaway.getDeliveryPrice());
//                    oFlowMoney.setDeliveryId(oDeliveryInfo.getId());
//                    oFlowMoney.setInflowDirection(1);
//                    if(oFlowMoneyMapper.insert(oFlowMoney) == 0){
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                        return Result.error("抢单失败");
//                    }
//                }
//                return Result.ok("抢单成功");
//            }
//        }
        List<OrderTakeaway> oOrderTakeawayList = new ArrayList<>();
        long total = 0;
        queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(0));
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_ID.eq(oDeliveryInfo.getSchoolId()));
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.CREATE_TIME.le(DateUtils.getNowMinute(5)));
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(1));
        queryWrapper.orderBy("pay_time asc");
        queryWrapper.limit(1);
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneByQuery(queryWrapper);
        if(oOrderTakeaway != null){
            oOrderTakeaway.setDeliveryState(1);
            oOrderTakeaway.setConnectTime(new Date());
            if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("抢单失败");
            }
            //添加外卖订单配送
            OrderDelivery oOrderDelivery = new OrderDelivery();
            oOrderDelivery.setOrderTakeawayId(oOrderTakeaway.getId());
            oOrderDelivery.setDeliveryId(oOrderTakeawayDto.getDeliveryId());
            oOrderDelivery.setDeliveryState(0);
            if(oOrderDeliveryMapper.insert(oOrderDelivery) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("抢单失败");
            }
            //添加配送员业务流水
            UpdateChain.of(FlowBusiness.class)
                    .set(FlowBusiness::getDeliveryId, oDeliveryInfo.getId())
                    .where(FlowBusiness::getOrderId).eq(oOrderTakeaway.getId())
                    .update();
            //判断配送员是否是兼职
            if(oDeliveryInfo.getWorkType() == 0){

                //添加配送员金额流水
                FlowMoney oFlowMoney = new FlowMoney();
                oFlowMoney.setType(0);
                oFlowMoney.setInflowWay(0);
                oFlowMoney.setOrderId(oOrderTakeaway.getId());
                //获取兼职配送员每单收益
                oFlowMoney.setMoney(Double.valueOf(ComVariableUtil.getSystemValue("delivery_draw")));
                oFlowMoney.setDeliveryId(oDeliveryInfo.getId());
                oFlowMoney.setInflowDirection(1);
                if(oFlowMoneyMapper.insert(oFlowMoney) == 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return Result.error("抢单失败");
                }
            }
            return Result.ok("抢单成功");
        }
        return Result.ok("暂无订单可抢");
    }

    /**
     * 配送员取餐
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result takeOrderTakeawayToDelivery(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        //获取订单
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneById(oOrderTakeawayDto.getId());
        if(oOrderTakeaway.getDeliveryState() != 1){
            return Result.error("此订单已被取餐");
        }
        oOrderTakeaway.setDeliveryState(2);
        oOrderTakeaway.setShopState(2);
        oOrderTakeaway.setDeliveryType(oOrderTakeawayDto.getDeliveryType());
        //如果单人配送，默认已中转
        if(oOrderTakeaway.getDeliveryType() == 1){
            oOrderTakeaway.setIsTransfer(1);
        }
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("取餐失败");
        }
        //修改外卖订单配送
        UpdateChain.of(OrderDelivery.class)
                .set(OrderDelivery::getDeliveryState, 1)
                .set(OrderDelivery::getPickingTime, new Date())
                .where(OrderDelivery::getOrderTakeawayId).eq(oOrderTakeaway.getId())
                .where(OrderDelivery::getDeliveryId).eq(oOrderTakeawayDto.getDeliveryId())
                .update();
        return Result.ok("取餐成功");
    }

    /**
     * 生成中转订单二维码
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    public Result transferOrderTakeawayCode(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        //获取订单
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneById(oOrderTakeawayDto.getId());
        //判断订单状态是否正确
        if(oOrderTakeaway.getDeliveryState() != 2 || oOrderTakeaway.getIsTransfer() == 1){
            return Result.error("此订单已中转");
        }
        //获取登陆配送员
        if(StringUtils.isBlank(oOrderTakeawayDto.getDeliveryId())){
            return Result.error("请重新登录");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.ID.eq(oOrderTakeawayDto.getDeliveryId()));
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.STATE.eq(1));
        DeliveryInfo oDeliveryInfo = oDeliveryInfoMapper.selectOneByQuery(queryWrapper);
        if(oDeliveryInfo == null){
            return Result.error("配送员不存在");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("oOrderTakeawayId",oOrderTakeaway.getId());
        map.put("oDeliveryInfoId",oDeliveryInfo.getId());
        return Result.ok(QRCodeUtil.generateQRCode(new ObjectMapper().writeValueAsString(map)));
    }

    /**
     * 配送员中转订单
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result transferOrderTakeawayToDelivery(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        //获取订单
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneById(oOrderTakeawayDto.getId());
        //判断订单状态是否正确
        if(oOrderTakeaway.getDeliveryState() != 2 || oOrderTakeaway.getIsTransfer() == 1){
            return Result.error("此订单已中转");
        }
        System.out.println("------------------------------------");
        System.out.println("id() : " + oOrderTakeawayDto.getId());
        System.out.println("deliveryId() : " + oOrderTakeawayDto.getDeliveryId());
        System.out.println("transferDeliveryId() : " + oOrderTakeawayDto.getTransferDeliveryId());
        System.out.println("------------------------------------");
        //获取登陆配送员
        if(StringUtils.isBlank(oOrderTakeawayDto.getDeliveryId())){
            return Result.error("请重新登录");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.ID.eq(oOrderTakeawayDto.getDeliveryId()));
        queryWrapper.where(DeliveryInfoTableDef.DELIVERY_INFO.STATE.eq(1));
        DeliveryInfo oDeliveryInfo = oDeliveryInfoMapper.selectOneByQuery(queryWrapper);
        if(oDeliveryInfo == null){
            return Result.error("配送员不存在");
        }
        if(oDeliveryInfo.getExamineState() == 0){
            return Result.error("请先前往审核");
        }
        //修改订单信息
        oOrderTakeaway.setIsTransfer(1);
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("中转订单失败");
        }
        //修改中转前配送员
        UpdateChain.of(OrderDelivery.class)
                .set(OrderDelivery::getDeliveryState, 2)
                .set(OrderDelivery::getReachTime, new Date())
                .where(OrderDelivery::getOrderTakeawayId).eq(oOrderTakeaway.getId())
                .where(OrderDelivery::getDeliveryId).eq(oOrderTakeawayDto.getTransferDeliveryId())
                .update();
        //添加中转后配送员
        OrderDelivery oOrderDelivery = new OrderDelivery();
        oOrderDelivery.setOrderTakeawayId(oOrderTakeaway.getId());
        oOrderDelivery.setDeliveryId(oDeliveryInfo.getId());
        oOrderDelivery.setDeliveryState(1);
        if(oOrderDeliveryMapper.insert(oOrderDelivery) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("中转订单失败");
        }
        //添加配送员业务流水
        queryWrapper = new QueryWrapper();
        queryWrapper.where(FlowBusinessTableDef.FLOW_BUSINESS.ORDER_ID.eq(oOrderTakeaway.getId()));
        queryWrapper.where(FlowBusinessTableDef.FLOW_BUSINESS.ORDER_ID.eq(oOrderTakeaway.getId()));
        FlowBusiness oFlowBusiness = oFlowBusinessMapper.selectOneByQuery(queryWrapper);
        oFlowBusiness.setDeliveryId(oFlowBusiness.getDeliveryId() + "," + oDeliveryInfo.getId());
        if(oFlowBusinessMapper.update(oFlowBusiness) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("抢单失败");
        }
//        UpdateChain.of(FlowBusiness.class)
//                .setRaw(FlowBusiness::getDeliveryId, "delivery_id + " + "," + oDeliveryInfo.getId())
//                .where(FlowBusiness::getOrderId).eq(oOrderTakeaway.getId())
//                .update();
        //添加金额流水
        if(oDeliveryInfo.getWorkType() == 0){
            //添加配送员金额流水
            FlowMoney oFlowMoney = new FlowMoney();
            oFlowMoney.setType(0);
            oFlowMoney.setInflowWay(0);
            oFlowMoney.setOrderId(oOrderTakeaway.getId());
            //获取兼职配送员每单收益
            oFlowMoney.setMoney(Double.valueOf(ComVariableUtil.getSystemValue("delivery_draw")));
            oFlowMoney.setDeliveryId(oDeliveryInfo.getId());
            oFlowMoney.setInflowDirection(1);
            if(oFlowMoneyMapper.insert(oFlowMoney) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("抢单失败");
            }
        }
        return Result.ok();
    }

    /**
     * 配送员确认完成
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result okOrderTakeawayToDelivery(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        //获取订单
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneById(oOrderTakeawayDto.getId());
        if(oOrderTakeaway.getDeliveryType() != 1){
            return Result.error("订单还未完成中转");
        }
        if(oOrderTakeaway.getDeliveryState() != 2){
            return Result.error("配送员已确认完成");
        }
        oOrderTakeaway.setDeliveryState(3);
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("确认完成失败");
        }
        //修改外卖订单配送
        UpdateChain.of(OrderDelivery.class)
                .set(OrderDelivery::getDeliveryState, 2)
                .set(OrderDelivery::getReachTime, new Date())
                .where(OrderDelivery::getOrderTakeawayId).eq(oOrderTakeaway.getId())
                .where(OrderDelivery::getDeliveryId).eq(oOrderTakeawayDto.getDeliveryId())
                .update();
        //进入用户确认完成
        long delay = 30 * 60 * 1000;
        new DelayedActive().delaySend(new ActiveMQQueue("automaticOkOrderTakeawayToUser"),oOrderTakeaway.getId(),delay);
        //获取用户信息
        UserInfo oUserInfo = oUserInfoMapper.selectOneById(oOrderTakeaway.getUserId());
        //推送消息
        Map<String,String> pushMap = new HashMap<>();
        pushMap.put("type","外卖订单");
        pushMap.put("oOrderTakeawayId",oOrderTakeaway.getId());
        pushMap.put("state","已送达");
        pushMap.put("content","您的订单已送达");
        wxMessagesManager.pushWxMessages(oUserInfo.getWxOptionId(),pushMap);
        return Result.ok("确认完成成功");

    }

    /**
     * 获取外卖订单（配送员）
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getOrderTakeawayToDelivery(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        List<OrderTakeaway> oOrderTakeawayList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入配送员ID
        QueryWrapper qrOrderDelivery = new QueryWrapper();
        qrOrderDelivery.where(OrderDeliveryTableDef.ORDER_DELIVERY.DELIVERY_ID.eq(oOrderTakeawayDto.getDeliveryId()));
        List<OrderDelivery> oOrderDeliveryList = oOrderDeliveryMapper.selectListByQuery(qrOrderDelivery);
        if(CollectionUtils.isEmpty(oOrderDeliveryList)){
            return Result.ok(new ArrayList(),total);
        }
        //获取查到的订单ID集合
        List<String> oOrderTakeawayIdList = new ArrayList<>();
        oOrderDeliveryList.forEach(item->{oOrderTakeawayIdList.add(item.getOrderTakeawayId());});
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.ID.in(oOrderTakeawayIdList));
        //判断是否传入店铺ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getShopId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_ID.eq(oOrderTakeawayDto.getShopId()));
        }
        //判断是否传入校区ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getSchoolId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_ID.eq(oOrderTakeawayDto.getSchoolId()));
        }
        //判断是否传入校区楼栋ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getSchoolBuildingId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_BUILDING_ID.eq(oOrderTakeawayDto.getSchoolBuildingId()));
        }
        //判断是否传入配送状态
        if(oOrderTakeawayDto.getDeliveryState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(oOrderTakeawayDto.getDeliveryState()));
        }
        //判断是否传入出餐状态
        if(oOrderTakeawayDto.getShopState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_STATE.eq(oOrderTakeawayDto.getShopState()));
        }
        //判断是否传入查询开始结束时间
        if(oOrderTakeawayDto.getQueryBeginTime() != null && oOrderTakeawayDto.getQueryEndTime() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.CONNECT_TIME.between(oOrderTakeawayDto.getQueryBeginTime(),oOrderTakeawayDto.getQueryEndTime()));
        }
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(1));
        queryWrapper.orderBy("connect_time desc");
        //是否分页
        if(oOrderTakeawayDto.getPage() != null && oOrderTakeawayDto.getLimit() != null){
            Page<OrderTakeaway> OrderTakeawayPage = oOrderTakeawayMapper.paginateWithRelations(oOrderTakeawayDto.getPage(),oOrderTakeawayDto.getLimit(),queryWrapper);
            oOrderTakeawayList = OrderTakeawayPage.getRecords();
            total = OrderTakeawayPage.getTotalRow();
        }else{
            oOrderTakeawayList = oOrderTakeawayMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oOrderTakeawayList.size();
        }
        //PoToDto
        List<OrderTakeawayDto> oOrderTakeawayDtoList = (List<OrderTakeawayDto>) PoToDTO.poToDtoList(oOrderTakeawayList,new OrderTakeawayDto());
        return Result.ok(oOrderTakeawayDtoList,total);
    }

    /**
     * 获取外卖订单（商家）
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getOrderTakeawayToShop(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        List<OrderTakeaway> oOrderTakeawayList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入店铺ID
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_ID.eq(oOrderTakeawayDto.getShopId()));
        //判断是否传入配送员ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getDeliveryId())){
            QueryWrapper qrOrderDelivery = new QueryWrapper();
            qrOrderDelivery.where(OrderDeliveryTableDef.ORDER_DELIVERY.DELIVERY_ID.eq(oOrderTakeawayDto.getDeliveryId()));
            List<OrderDelivery> oOrderDeliveryList = oOrderDeliveryMapper.selectListByQuery(qrOrderDelivery);
            if(CollectionUtils.isEmpty(oOrderDeliveryList)){
                return Result.ok(new ArrayList(),total);
            }
            //获取查到的订单ID集合
            List<String> oOrderTakeawayIdList = new ArrayList<>();
            oOrderDeliveryList.forEach(item->{oOrderTakeawayIdList.add(item.getOrderTakeawayId());});
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.ID.in(oOrderTakeawayIdList));
        }
        //判断是否传入校区ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getSchoolId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_ID.eq(oOrderTakeawayDto.getSchoolId()));
        }
        //判断是否传入校区楼栋ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getSchoolBuildingId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_BUILDING_ID.eq(oOrderTakeawayDto.getSchoolBuildingId()));
        }
        //判断是否传入配送状态
        if(oOrderTakeawayDto.getDeliveryState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(oOrderTakeawayDto.getDeliveryState()));
        }
        //判断是否传入出餐状态
        if(oOrderTakeawayDto.getShopState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_STATE.eq(oOrderTakeawayDto.getShopState()));
        }
        //判断是否传入查询开始结束时间
        if(oOrderTakeawayDto.getQueryBeginTime() != null && oOrderTakeawayDto.getQueryEndTime() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.CREATE_TIME.between(oOrderTakeawayDto.getQueryBeginTime(),oOrderTakeawayDto.getQueryEndTime()));
        }
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(1));
        queryWrapper.orderBy("pay_time desc,call_number desc");
        //是否分页
        if(oOrderTakeawayDto.getPage() != null && oOrderTakeawayDto.getLimit() != null){
            Page<OrderTakeaway> OrderTakeawayPage = oOrderTakeawayMapper.paginateWithRelations(oOrderTakeawayDto.getPage(),oOrderTakeawayDto.getLimit(),queryWrapper);
            oOrderTakeawayList = OrderTakeawayPage.getRecords();
            total = OrderTakeawayPage.getTotalRow();
        }else{
            oOrderTakeawayList = oOrderTakeawayMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oOrderTakeawayList.size();
        }
        //PoToDto
        List<OrderTakeawayDto> oOrderTakeawayDtoList = (List<OrderTakeawayDto>) PoToDTO.poToDtoList(oOrderTakeawayList,new OrderTakeawayDto());
        return Result.ok(oOrderTakeawayDtoList,total);
    }

    /**
     * 微信支付外卖订单成功（回调）
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Map<String, String> wxPayOrderTakeawayCallback(JSONObject jsonObject) throws Exception {
        try{
            System.out.println("-------------------------------------------");
            System.out.println("回调数据" + jsonObject);
            System.out.println("-------------------------------------------");
            String oOrderTakeawayId = oWeiXinPayService.notifyOrder(jsonObject).get("out_trade_no").toString();
            if(StringUtils.isNotBlank(oOrderTakeawayId)){
                //处理微信流水
                UpdateChain.of(ComPayFlow.class)
                        .set(ComPayFlow::getState, 1)
                        .where(ComPayFlow::getType).eq(0)
                        .where(ComPayFlow::getOrderId).eq(oOrderTakeawayId)
                        .update();
                wxPayOrderTakeawayCallback(oOrderTakeawayId);
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }finally {
            Map<String, String> res = new HashMap<>();
            res.put("code", "SUCCESS");
            res.put("message", "成功");
            return res;
        }
    }

    /**
     * 微信支付外卖订单成功（回调业务逻辑）
     * @param orderTakeawayId 订单ID
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public void wxPayOrderTakeawayCallback(String orderTakeawayId) throws Exception {
        //重新获取订单信息
        RelationManager.setMaxDepth(1);
        RelationManager.addQueryRelations("orderTakeawayCommodityList");
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneWithRelationsById(orderTakeawayId);
        //修改订单信息
        //设置叫号
        //获取当日叫号
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper = new QueryWrapper();
        Date time = new Date();
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_TIME.between(DateUtil.beginOfDay(time),DateUtil.endOfDay(time)));
        queryWrapper.orderBy("call_number desc");
        queryWrapper.limit(1);
        OrderTakeaway lastOrderTakeaway = oOrderTakeawayMapper.selectOneByQuery(queryWrapper);
        if(lastOrderTakeaway == null){
            oOrderTakeaway.setCallNumber(1000);
        }else{
            oOrderTakeaway.setCallNumber(lastOrderTakeaway.getCallNumber() + 1);
        }
        oOrderTakeaway.setPaymentMethod(0);
        oOrderTakeaway.setPayState(1);
        oOrderTakeaway.setPayTime(time);
        //修改节省金额
        oOrderTakeaway.setSavingsPrice(0.0);
        //创建存储金额比例过程集合
        Map<String,Object> map = new HashMap<>();
        //平台订单抽成比例
        Double comDraw = Double.valueOf(ComVariableUtil.getSystemValue("com_orderTakeaway_draw"));
        map.put("comDraw",comDraw);
        //真实商品金额
        Double actualCommodity = new BigDecimal(oOrderTakeaway.getPrice() - oOrderTakeaway.getPackingCharge() - oOrderTakeaway.getDeliveryPrice()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        map.put("actualCommodity",actualCommodity);
        //平台抽取商品金额
        Double comCommodity = new BigDecimal(actualCommodity * comDraw).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        map.put("comCommodity",comCommodity);
        //计算平台抽取的总费用
        Double comAll = new BigDecimal(comCommodity + oOrderTakeaway.getPackingCharge() + oOrderTakeaway.getDeliveryPrice()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();;
        map.put("comAll",comAll);
        oOrderTakeaway.setComDraw(new GsonBuilder().enableComplexMapKeySerialization().create().toJson(map));
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("储蓄支付外卖订单失败");
        }
        //创建添加金额流水集合
        List<FlowMoney> oFlowMoneyList = new ArrayList<>();
        //创建店铺金额流水
        FlowMoney oShopFlowMoney = new FlowMoney();
        oShopFlowMoney.setShopId(oOrderTakeaway.getShopId());
        oShopFlowMoney.setType(0);
        oShopFlowMoney.setInflowDirection(1);
        oShopFlowMoney.setInflowWay(0);
        oShopFlowMoney.setOrderId(oOrderTakeaway.getId());
        oShopFlowMoney.setMoney(oOrderTakeaway.getPrice() - comAll);
        oFlowMoneyList.add(oShopFlowMoney);
        //创建平台金额流水
        FlowMoney oSystemFlowMoney = new FlowMoney();
        oSystemFlowMoney.setType(0);
        oSystemFlowMoney.setInflowDirection(0);
        oSystemFlowMoney.setInflowWay(0);
        oSystemFlowMoney.setOrderId(oOrderTakeaway.getId());
        oSystemFlowMoney.setMoney(comAll);
        oFlowMoneyList.add(oSystemFlowMoney);
        //创建用户金额流水（积分）
        FlowMoney oUserIntegralFlowMoney = new FlowMoney();
        oUserIntegralFlowMoney.setUserId(oOrderTakeaway.getUserId());
        oUserIntegralFlowMoney.setType(0);
        oUserIntegralFlowMoney.setInflowDirection(1);
        oUserIntegralFlowMoney.setInflowWay(1);
        oUserIntegralFlowMoney.setOrderId(oOrderTakeaway.getId());
        oUserIntegralFlowMoney.setIntegral(oOrderTakeaway.getPrice().intValue());
        oFlowMoneyList.add(oUserIntegralFlowMoney);
        //创建用户金额流水（分销商）
        //获取用户信息
        UserInfo oUserInfo = oUserInfoMapper.selectOneById(oOrderTakeaway.getUserId());
        if(StringUtils.isNotBlank(oUserInfo.getInvitationCode())){
            //获取推荐人信息
            queryWrapper = new QueryWrapper();
            queryWrapper.where(UserInfoTableDef.USER_INFO.ID.eq(oUserInfo.getInvitationCode()));
            queryWrapper.where(UserInfoTableDef.USER_INFO.STATE.eq(1));
            UserInfo codeUserInfo = oUserInfoMapper.selectOneByQuery(queryWrapper);
            if(codeUserInfo != null && codeUserInfo.getIsDistribution() != 3){
                //获取分销商等级规则
                queryWrapper = new QueryWrapper();
                queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.GRADE.eq(codeUserInfo.getDistributionGrade()));
                queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.TYPE.eq(codeUserInfo.getIsDistribution()));
                ComDistributionRule oComDistributionRule = oComDistributionRuleMapper.selectOneByQuery(queryWrapper);
                if(oComDistributionRule != null){
                    //创建用户金额流水（分销商）
                    FlowMoney oUserDistributionFlowMoney = new FlowMoney();
                    oUserDistributionFlowMoney.setUserId(codeUserInfo.getId());
                    oUserDistributionFlowMoney.setType(0);
                    oUserDistributionFlowMoney.setInflowDirection(1);
                    oUserDistributionFlowMoney.setInflowWay(0);
                    oUserDistributionFlowMoney.setOrderId(oOrderTakeaway.getId());
                    oUserDistributionFlowMoney.setMoney((oOrderTakeaway.getPrice()) * oComDistributionRule.getCommission());
                    oFlowMoneyList.add(oUserDistributionFlowMoney);
                }
            }
        }
        //添加金额流水集合
        if(oFlowMoneyMapper.insertBatch(oFlowMoneyList) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("微信支付失败");
        }
        //修改店铺销量
        UpdateChain.of(ShopInfo.class).setRaw(ShopInfo::getSalesVolume, "sales_volume + 1").where(ShopInfo::getId).eq(oOrderTakeaway.getShopId()).update();
        //修改商品销量
        ShopCommodity oShopCommodity = new ShopCommodity();
        for(OrderTakeawayCommodity oOrderTakeawayCommodity : oOrderTakeaway.getOrderTakeawayCommodityList()){
            UpdateChain.of(ShopCommodity.class).setRaw(ShopCommodity::getSalesVolume, "sales_volume + 1").where(ShopCommodity::getId).eq(oOrderTakeawayCommodity.getCommodityId()).update();
        }
        //获取店铺信息
        ShopInfo oShopInfo = oShopInfoMapper.selectOneById(oOrderTakeaway.getShopId());
        //判断店铺是否开启自动出餐
        if(oShopInfo.getIsDining() == 1){
            long delay = oShopInfo.getDiningTime() * 60 * 1000;
            new DelayedActive().delaySend(new ActiveMQQueue("automaticDiningOrderTakeawayToShop"),oOrderTakeaway.getId(),delay);
        }
        //推送消息
        Map<String,String> pushMap = new HashMap<>();
        pushMap.put("type","外卖订单");
        pushMap.put("oOrderTakeawayId",oOrderTakeaway.getId());
        pushMap.put("state","已下单");
        pushMap.put("content","您的订单已下单成功");
        wxMessagesManager.pushWxMessages(oUserInfo.getWxOptionId(),pushMap);
    }

    /**
     * 储蓄支付外卖订单成功（回调）
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public Result savePayOrderTakeawayCallback(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        OrderTakeaway oOrderTakeaway = new OrderTakeaway();
        PoToDTO.poToDto(oOrderTakeawayDto,oOrderTakeaway);
        //获取用户的储蓄余额
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopSaveUserTableDef.SHOP_SAVE_USER.USER_ID.eq(oOrderTakeawayDto.getUserId()));
        queryWrapper.where(ShopSaveUserTableDef.SHOP_SAVE_USER.SHOP_ID.eq(oOrderTakeawayDto.getShopId()));
        queryWrapper.where(ShopSaveUserTableDef.SHOP_SAVE_USER.IS_SPEND.eq(0));
        queryWrapper.orderBy("create_time,user_balance asc");
        List<ShopSaveUser> oShopSaveUserList = oShopSaveUserMapper.selectListByQuery(queryWrapper);
        if(CollectionUtil.isEmpty(oShopSaveUserList)){
            return Result.error("用户还不是此店铺的储蓄会员");
        }
        Double userBalance = 0.0;
        for(ShopSaveUser oShopSaveUser : oShopSaveUserList){
            userBalance += oShopSaveUser.getUserBalance();
            if(userBalance.compareTo(oOrderTakeawayDto.getPrice()) >= 0){
                break;
            }
        }
        if(userBalance.compareTo(oOrderTakeawayDto.getPrice()) < 0){
            return Result.error("用户储蓄余额不足");
        }
        //扣除余额
        //创建需要修改的用户储蓄充值集合
        List<ShopSaveUser> updateShopSaveUser = new ArrayList<>();
        //创建订单储蓄支付缓存集合
        List<OrderTakeawaySaveCache> oOrderTakeawaySaveCacheList = new ArrayList<>();
        //创建每一个储蓄余额扣减下来的剩余还需支付的金额
        Double payPrice = oOrderTakeawayDto.getPrice();
        //创建这一单储蓄支付后实际应得的价格
        Double actualPrice = 0.0;
        for(ShopSaveUser oShopSaveUser : oShopSaveUserList){
            if(payPrice <= 0){
                break;
            }
            //创建订单储蓄支付缓存
            OrderTakeawaySaveCache oOrderTakeawaySaveCache = new OrderTakeawaySaveCache();
            oOrderTakeawaySaveCache.setOrderTakeawayId(oOrderTakeaway.getId());
            oOrderTakeawaySaveCache.setShopSaveUserId(oShopSaveUser.getId());
            //判断当前这条储蓄充值用户余额是否充足
            if(oShopSaveUser.getUserBalance().compareTo(payPrice) > 0){
                oShopSaveUser.setUserBalance(oShopSaveUser.getUserBalance() - payPrice);
                actualPrice += new BigDecimal(payPrice * oShopSaveUser.getDiscountRatio()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                oOrderTakeawaySaveCache.setUserPrice(payPrice);
                payPrice = 0.0;
            }else {
                oOrderTakeawaySaveCache.setUserPrice(oShopSaveUser.getUserBalance());
                actualPrice += new BigDecimal(oShopSaveUser.getUserBalance() * oShopSaveUser.getDiscountRatio()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                payPrice -= oShopSaveUser.getUserBalance();
                oShopSaveUser.setUserBalance(0.0);
                oShopSaveUser.setIsSpend(1);
            }
            oOrderTakeawaySaveCacheList.add(oOrderTakeawaySaveCache);
            updateShopSaveUser.add(oShopSaveUser);
        }
        //修改用户储蓄充值余额
        for(ShopSaveUser oShopSaveUser : updateShopSaveUser){
            if(oShopSaveUserMapper.update(oShopSaveUser) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new Exception("储蓄支付外卖订单失败");
            }
        }
        //添加订单储蓄支付缓存集合
        if(oOrderTakeawaySaveCacheMapper.insertBatch(oOrderTakeawaySaveCacheList) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("储蓄支付外卖订单失败");
        }
        //修改订单信息
        //设置叫号
        //获取当日叫号
        queryWrapper = new QueryWrapper();
        Date time = new Date();
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_TIME.between(DateUtil.beginOfDay(time),DateUtil.endOfDay(time)));
        queryWrapper.orderBy("call_number desc");
        queryWrapper.limit(1);
        OrderTakeaway lastOrderTakeaway = oOrderTakeawayMapper.selectOneByQuery(queryWrapper);
        if(lastOrderTakeaway == null){
            oOrderTakeaway.setCallNumber(1000);
        }else{
            oOrderTakeaway.setCallNumber(lastOrderTakeaway.getCallNumber() + 1);
        }
        oOrderTakeaway.setPaymentMethod(1);
        oOrderTakeaway.setPayState(1);
        oOrderTakeaway.setPayTime(time);
        //计算订单原价扣减店铺规则后的剩余价格
        Double originalPrice = getOrderTakeawayPrice(oOrderTakeawayDto.getOriginalPrice(), oOrderTakeaway.getShopId(), oOrderTakeaway.getUserId(), oOrderTakeaway.getId());
        //计算订单会员价扣减店铺规则后的剩余价格
        Double memberPrice = getOrderTakeawayPrice(oOrderTakeawayDto.getMemberPrice(), oOrderTakeaway.getShopId(), oOrderTakeaway.getUserId(), oOrderTakeaway.getId());
        //修改节省金额
        if(originalPrice.compareTo(memberPrice) > 0){
            oOrderTakeaway.setSavingsPrice(originalPrice - memberPrice);
        }
        //创建存储金额比例过程集合
        Map<String,Object> map = new HashMap<>();
        //储蓄价格
        map.put("price",oOrderTakeaway.getPrice());
        //真实价格
        map.put("actualPrice",actualPrice);
        //真实支付比例
        Double actualDraw = new BigDecimal(actualPrice / oOrderTakeaway.getPrice()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        map.put("actualDraw",actualDraw);
        //平台订单抽成比例
        Double comDraw = Double.valueOf(ComVariableUtil.getSystemValue("com_orderTakeaway_draw"));
        map.put("comDraw",comDraw);
        //平台抽取打包费
        Double comPackingCharge = new BigDecimal(oOrderTakeaway.getPackingCharge() * actualDraw).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        map.put("comPackingCharge",comPackingCharge);
        //平台抽取配送费
        Double comDeliveryPrice = new BigDecimal(oOrderTakeaway.getDeliveryPrice() * actualDraw).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        map.put("comDeliveryPrice",comDeliveryPrice);
        //真实商品金额
        Double actualCommodity = new BigDecimal(actualPrice - comPackingCharge - comDeliveryPrice).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        map.put("actualCommodity",actualCommodity);
        //平台抽取商品金额
        Double comCommodity = new BigDecimal(actualCommodity * comDraw).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        map.put("comCommodity",comCommodity);
        //计算平台抽取的总费用
        Double comAll = new BigDecimal(comCommodity + comPackingCharge + comDeliveryPrice).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();;
        map.put("comAll",comAll);
        oOrderTakeaway.setComDraw(new GsonBuilder().enableComplexMapKeySerialization().create().toJson(map));
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("储蓄支付外卖订单失败");
        }
        //创建添加金额流水集合
        List<FlowMoney> oFlowMoneyList = new ArrayList<>();
        //创建店铺金额流水
        FlowMoney oShopFlowMoney = new FlowMoney();
        oShopFlowMoney.setShopId(oOrderTakeaway.getShopId());
        oShopFlowMoney.setType(0);
        oShopFlowMoney.setInflowDirection(1);
        oShopFlowMoney.setInflowWay(0);
        oShopFlowMoney.setOrderId(oOrderTakeaway.getId());
        oShopFlowMoney.setMoney(actualPrice - comAll);
        oFlowMoneyList.add(oShopFlowMoney);
        //创建平台金额流水
        FlowMoney oSystemFlowMoney = new FlowMoney();
        oSystemFlowMoney.setType(0);
        oSystemFlowMoney.setInflowDirection(0);
        oSystemFlowMoney.setInflowWay(0);
        oSystemFlowMoney.setOrderId(oOrderTakeaway.getId());
        oSystemFlowMoney.setMoney(comAll);
        oFlowMoneyList.add(oSystemFlowMoney);
        //创建用户金额流水（积分）
        FlowMoney oUserIntegralFlowMoney = new FlowMoney();
        oUserIntegralFlowMoney.setUserId(oOrderTakeaway.getUserId());
        oUserIntegralFlowMoney.setType(0);
        oUserIntegralFlowMoney.setInflowDirection(1);
        oUserIntegralFlowMoney.setInflowWay(1);
        oUserIntegralFlowMoney.setOrderId(oOrderTakeaway.getId());
        oUserIntegralFlowMoney.setIntegral(oOrderTakeaway.getPrice().intValue());
        oFlowMoneyList.add(oUserIntegralFlowMoney);
        //创建用户金额流水（分销商）
        //获取用户信息
        UserInfo oUserInfo = oUserInfoMapper.selectOneById(oOrderTakeaway.getUserId());
        if(StringUtils.isNotBlank(oUserInfo.getInvitationCode())){
            //获取推荐人信息
            queryWrapper = new QueryWrapper();
            queryWrapper.where(UserInfoTableDef.USER_INFO.ID.eq(oUserInfo.getInvitationCode()));
            queryWrapper.where(UserInfoTableDef.USER_INFO.STATE.eq(1));
            UserInfo codeUserInfo = oUserInfoMapper.selectOneByQuery(queryWrapper);
            if(codeUserInfo != null && codeUserInfo.getIsDistribution() != 3){
                //获取分销商等级规则
                queryWrapper = new QueryWrapper();
                queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.GRADE.eq(codeUserInfo.getDistributionGrade()));
                queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.TYPE.eq(codeUserInfo.getIsDistribution()));
                ComDistributionRule oComDistributionRule = oComDistributionRuleMapper.selectOneByQuery(queryWrapper);
                if(oComDistributionRule != null){
                    //创建用户金额流水（分销商）
                    FlowMoney oUserDistributionFlowMoney = new FlowMoney();
                    oUserDistributionFlowMoney.setUserId(codeUserInfo.getId());
                    oUserDistributionFlowMoney.setType(0);
                    oUserDistributionFlowMoney.setInflowDirection(1);
                    oUserDistributionFlowMoney.setInflowWay(0);
                    oUserDistributionFlowMoney.setOrderId(oOrderTakeaway.getId());
                    oUserDistributionFlowMoney.setMoney(actualPrice * oComDistributionRule.getCommission());
                    oFlowMoneyList.add(oUserDistributionFlowMoney);
                }
            }
        }
        //添加金额流水集合
        if(oFlowMoneyMapper.insertBatch(oFlowMoneyList) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("储蓄支付失败");
        }
        //修改店铺销量
        UpdateChain.of(ShopInfo.class).setRaw(ShopInfo::getSalesVolume, "sales_volume + 1").where(ShopInfo::getId).eq(oOrderTakeaway.getShopId()).update();
        //修改商品销量
        ShopCommodity oShopCommodity = new ShopCommodity();
        for(OrderTakeawayCommodity oOrderTakeawayCommodity : oOrderTakeawayDto.getOrderTakeawayCommodityList()){
            UpdateChain.of(ShopCommodity.class).setRaw(ShopCommodity::getSalesVolume, "sales_volume + 1").where(ShopCommodity::getId).eq(oOrderTakeawayCommodity.getCommodityId()).update();
        }
        //获取店铺信息
        ShopInfo oShopInfo = oShopInfoMapper.selectOneById(oOrderTakeaway.getShopId());
        //判断店铺是否开启自动出餐
        if(oShopInfo.getIsDining() == 1){
            long delay = oShopInfo.getDiningTime() * 60 * 1000;
            new DelayedActive().delaySend(new ActiveMQQueue("automaticDiningOrderTakeawayToShop"),oOrderTakeaway.getId(),delay);
        }
        //推送消息
        Map<String,String> pushMap = new HashMap<>();
        pushMap.put("type","外卖订单");
        pushMap.put("oOrderTakeawayId",oOrderTakeaway.getId());
        pushMap.put("state","已下单");
        pushMap.put("content","您的订单已下单成功");
        wxMessagesManager.pushWxMessages(oUserInfo.getWxOptionId(),pushMap);
        return Result.ok();
    }

    //计算订单价格扣减店铺规则后的剩余价格
    public Double getOrderTakeawayPrice(Double price, String shopId, String userId, String orderTakeawayId){
        //获取店铺规则
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopRuleTableDef.SHOP_RULE.SHOP_ID.eq(shopId));
        queryWrapper.orderBy("type asc,reach_price desc");
        List<ShopRule> oShopRuleList = oShopRuleMapper.selectListByQuery(queryWrapper);
        if(CollectionUtils.isEmpty(oShopRuleList)){
            return price;
        }
        //获取用户是否是店铺新人
        Boolean isNew = false;
        //获取用户在此店铺的订单
        queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.USER_ID.eq(userId));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.SHOP_ID.eq(shopId));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.ID.ne(orderTakeawayId));
        if(oOrderTakeawayMapper.selectCountByQuery(queryWrapper) == 0){
            isNew = true;
        }
        for(ShopRule oShopRule : oShopRuleList){
            //先首单
            if(oShopRule.getType() == 0){
                if(isNew){
                    price -= oShopRule.getGivePrice();
                }
            }else if(price.compareTo(oShopRule.getReachPrice()) >= 0){
                //再满减
                price -= oShopRule.getGivePrice();
                break;
            }
        }
        return price;
    }

    /**
     * 客户确认完成
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    public Result okOrderTakeawayToUser(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        try {
            automaticOkOrderTakeawayToUser(oOrderTakeawayDto.getId());
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 客户自动确认完成
     * @param oOrderTakeawayId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public void automaticOkOrderTakeawayToUser(String oOrderTakeawayId) throws Exception {
        if(StringUtils.isBlank(oOrderTakeawayId)){
            throw new Exception("客户确认完成失败");
        }
        //重新获取订单
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.ID.eq(oOrderTakeawayId));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.PAY_STATE.eq(1));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.SHOP_STATE.eq(2));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.DELIVERY_STATE.eq(3));
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneByQuery(queryWrapper);
        if(oOrderTakeaway == null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("订单已完成或被投诉");
        }
        oOrderTakeaway.setPayState(2);
        oOrderTakeaway.setOkTime(new Date());
        //修改订单信息
        if(oOrderTakeawayMapper.update(oOrderTakeaway) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("客户确认完成失败");
        }
        //修改业务流水
        FlowBusiness oFlowBusiness = new FlowBusiness();
        oFlowBusiness.setState(1);
        queryWrapper = new QueryWrapper();
        queryWrapper.where(FlowBusinessTable.FLOW_BUSINESS_TABLE.ORDER_ID.eq(oOrderTakeaway.getId()));
        if(oFlowBusinessMapper.updateByQuery(oFlowBusiness,queryWrapper) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("客户确认完成失败");
        }
        //获取金额流水
        queryWrapper = new QueryWrapper();
        queryWrapper.where(FlowMoneyTableDef.FLOW_MONEY.ORDER_ID.eq(oOrderTakeaway.getId()));
        List<FlowMoney> oFlowMoneyList = oFlowMoneyMapper.selectListByQuery(queryWrapper);
        if(CollectionUtils.isEmpty(oFlowMoneyList)){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("金额流水不存在");
        }
        //创建执行计划集合
        List<FlowTask> oFlowTaskList = new ArrayList<>();
        for(FlowMoney oFlowMoney : oFlowMoneyList){
            oFlowMoney.setState(1);
            if(oFlowMoneyMapper.update(oFlowMoney) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new Exception("客户确认完成失败");
            }
            //方向为流出
            if(oFlowMoney.getInflowDirection() == 1){
                //判断是否是积分流水
                if(oFlowMoney.getInflowWay() == 1){
                    UpdateChain.of(UserInfo.class)
                            .setRaw(UserInfo::getIntegral, "integral + " + oFlowMoney.getMoney())
                            .where(UserInfo::getId).eq(oOrderTakeaway.getUserId())
                            .update();
                }else{
                    //创建执行计划
                    FlowTask oFlowTask = new FlowTask();
                    PoToDTO.poToDto(oFlowMoney,oFlowTask);
                    oFlowTask.setId(null);
                    oFlowTaskList.add(oFlowTask);
                }
            }
        }
        //创建执行计划
        if(oFlowTaskMapper.insertBatch(oFlowTaskList) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("客户确认完成失败");
        }
        Double actualPrice = 0.0;
        //判断支付方式
        if(oOrderTakeaway.getPaymentMethod() == 1){
            //获取订单的存储金额比例过程
            Map<String, Double> oComDrawMap = JSONObject.parseObject(oOrderTakeaway.getComDraw(), new TypeReference<HashMap<String, Double>>() {
            });
            actualPrice = oComDrawMap.get("actualPrice");
        }else{
            actualPrice = oOrderTakeaway.getPrice();
        }
        //修改用户信息
        UpdateChain.of(UserInfo.class)
                .setRaw(UserInfo::getConsumptionPrice, "consumption_price + " + actualPrice)
                .setRaw(UserInfo::getSavingsPrice, "savings_price + " + oOrderTakeaway.getSavingsPrice())
                .where(UserInfo::getId).eq(oOrderTakeaway.getUserId())
                .update();
        //进入用户自动评价
        long delay = 30 * 60 * 1000;
        new DelayedActive().delaySend(new ActiveMQQueue("automaticShopCommodityEvaluate"),oOrderTakeaway.getId(),delay);
    }

    /**
     * 自动删除外卖订单
     * @param oOrderTakeawayId
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public void automaticDeleteOrderTakeaway(String oOrderTakeawayId) throws Exception {
        if(StringUtils.isBlank(oOrderTakeawayId)){
            throw new Exception("删除外卖订单失败");
        }
        //重新获取订单
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.ID.eq(oOrderTakeawayId));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.PAY_STATE.eq(0));
        OrderTakeaway oOrderTakeaway = oOrderTakeawayMapper.selectOneByQuery(queryWrapper);
        if(oOrderTakeaway != null){
            //删除业务流水
            queryWrapper = new QueryWrapper();
            queryWrapper.where(FlowBusinessTable.FLOW_BUSINESS_TABLE.ORDER_ID.eq(oOrderTakeaway.getId()));
            if(oFlowBusinessMapper.deleteByQuery(queryWrapper) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new Exception("删除外卖订单失败");
            }
            //删除支付订单商品
            queryWrapper = new QueryWrapper();
            queryWrapper.where(OrderTakeawayCommodityTableDef.ORDER_TAKEAWAY_COMMODITY.ORDER_TAKEAWAY_ID.eq(oOrderTakeaway.getId()));
            if(oOrderTakeawayCommodityMapper.deleteByQuery(queryWrapper) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new Exception("删除外卖订单失败");
            }
            //删除订单
            if(oOrderTakeawayMapper.deleteById(oOrderTakeaway.getId()) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new Exception("删除外卖订单失败");
            }
        }
    }

    /**
     * 获取外卖订单（用户）
     * @param oOrderTakeawayDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getOrderTakeawayToUser(OrderTakeawayDto oOrderTakeawayDto) throws Exception {
        List<OrderTakeaway> oOrderTakeawayList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入用户ID
        queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.USER_ID.eq(oOrderTakeawayDto.getUserId()));
        //判断是否传入ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.ID.eq(oOrderTakeawayDto.getId()));
        }
        //判断是否传入配送员ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getDeliveryId())){
            QueryWrapper qrOrderDelivery = new QueryWrapper();
            qrOrderDelivery.where(OrderDeliveryTableDef.ORDER_DELIVERY.DELIVERY_ID.eq(oOrderTakeawayDto.getDeliveryId()));
            List<OrderDelivery> oOrderDeliveryList = oOrderDeliveryMapper.selectListByQuery(qrOrderDelivery);
            if(CollectionUtils.isEmpty(oOrderDeliveryList)){
                return Result.ok(new ArrayList(),total);
            }
            //获取查到的订单ID集合
            List<String> oOrderTakeawayIdList = new ArrayList<>();
            oOrderDeliveryList.forEach(item->{oOrderTakeawayIdList.add(item.getOrderTakeawayId());});
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.ID.in(oOrderTakeawayIdList));
        }
        //判断是否传入店铺ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getShopId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_ID.eq(oOrderTakeawayDto.getShopId()));
        }
        //判断是否传入校区ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getSchoolId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_ID.eq(oOrderTakeawayDto.getSchoolId()));
        }
        //判断是否传入校区楼栋ID
        if(StringUtils.isNotBlank(oOrderTakeawayDto.getSchoolBuildingId())){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SCHOOL_BUILDING_ID.eq(oOrderTakeawayDto.getSchoolBuildingId()));
        }
        //判断是否传入支付状态
        if(oOrderTakeawayDto.getPayState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(oOrderTakeawayDto.getPayState()));
        }
        //判断是否传入配送状态
        if(oOrderTakeawayDto.getDeliveryState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(oOrderTakeawayDto.getDeliveryState()));
        }
        //判断是否传入出餐状态
        if(oOrderTakeawayDto.getShopState() != null){
            queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_STATE.eq(oOrderTakeawayDto.getShopState()));
        }
        //判断是否传入整体用户状态
        if(oOrderTakeawayDto.getWholeUserState() != null){
            if(oOrderTakeawayDto.getWholeUserState() == 0){
                queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(0));
            }else if(oOrderTakeawayDto.getWholeUserState() == 1){
                queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(1));
                queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_STATE.notIn(3,4));
            }else if(oOrderTakeawayDto.getWholeUserState() == 2){
                queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.eq(2));
                queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.DELIVERY_STATE.eq(3));
                queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_STATE.eq(2));
            }else if(oOrderTakeawayDto.getWholeUserState() == 3){
                queryWrapper.where(OrderTakeawayTable.ORDER_TAKEAWAY.PAY_STATE.in(3,4,5,6)).or(OrderTakeawayTable.ORDER_TAKEAWAY.SHOP_STATE.in(3,4));
            }
        }
        queryWrapper.orderBy("pay_time desc,create_time desc");
        //是否分页
        if(oOrderTakeawayDto.getPage() != null && oOrderTakeawayDto.getLimit() != null){
            Page<OrderTakeaway> OrderTakeawayPage = oOrderTakeawayMapper.paginateWithRelations(oOrderTakeawayDto.getPage(),oOrderTakeawayDto.getLimit(),queryWrapper);
            oOrderTakeawayList = OrderTakeawayPage.getRecords();
            total = OrderTakeawayPage.getTotalRow();
        }else{
            oOrderTakeawayList = oOrderTakeawayMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oOrderTakeawayList.size();
        }
        //PoToDto
        List<OrderTakeawayDto> oOrderTakeawayDtoList = (List<OrderTakeawayDto>) PoToDTO.poToDtoList(oOrderTakeawayList,new OrderTakeawayDto());
        oOrderTakeawayDtoList.forEach(item->{
            if(item.getPayState() == 0){
                item.setWholeUserState(0);
            }else if(item.getPayState() == 1 && item.getShopState() != 3 && item.getShopState() != 4){
                item.setWholeUserState(1);
            }else if(item.getPayState() == 2 && item.getIsEvaluate() == 0){
                item.setWholeUserState(2);
            }else if(item.getPayState() == 3 || item.getPayState() == 4 ||item.getPayState() == 5 || item.getPayState() == 6 || item.getShopState() == 3 || item.getShopState() == 4){
                item.setWholeUserState(3);
            }
        });
        return Result.ok(oOrderTakeawayDtoList,total);
    }

}
